// Copyright (C) 2011 YANG Hao (yangh2007@gmail.com). All rights reserved.
//
// This file is part of the (cute)octopus project.
//
// This file may be distributed and/or modified under the terms of the
// GNU General Public License version 2 as published by the Free Software
// Foundation.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Author(s): YANG Hao


#include "otask.h"

#include "oevent.h"
#include "odoc.h"

PRIVATE_BEGIN()
class OHandlerThread : public QThread {
public:
	OHandlerThread(int* ret, OTask* parent = 0) : QThread(parent), task(parent), ret_ptr(ret){}
	virtual void run() {*ret_ptr = task->exec();}
	OTask* task;
	int* ret_ptr;
};
PRIVATE_END()

OTask::OTask(Handler h, bool async /* = false */) 
: m_handler(h), m_ret(-1){
	if(async){
		m_asyncThread = new OPrivate::OHandlerThread(& m_ret, this);
		connect(m_asyncThread, SIGNAL(finished()), this, SIGNAL(finished()));
		connect(m_asyncThread, SIGNAL(terminated()), this, SIGNAL(terminated()));
	}
}

void OTask::start(){
	if(m_asyncThread){
		m_asyncThread->start();
	}else{
		int retval = exec(); 
		emit finished();
	}
}
OStd::TaskRet OTask::exec() {return m_handler();}

#include "otask.moc"